<template>
  <div class="knowledge-base-manage">
    <h2>知识库管理</h2>

    <!-- 加载状态 -->
    <el-skeleton :loading="loading" animated v-if="!knowledgeBases.length && totalRecords === 0"></el-skeleton>

    <el-table :data="knowledgeBases" style="width: 100%" border v-else>
      <el-table-column prop="id" label="ID" align="center"></el-table-column>
      <el-table-column prop="question" label="问题" align="left"></el-table-column>
      <el-table-column prop="answer" label="答案" align="left">
        <template #default="scope">
          <el-tooltip content="点击查看完整答案" placement="top">
            <span class="text-ellipsis">{{ scope.row.answer }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="category" label="分类" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 空数据状态 -->
    <div v-if="totalRecords === 0 && !loading" class="empty-state">
      <el-empty description="暂无知识库条目"></el-empty>
    </div>

    <div style="margin-top: 10px; display: flex; align-items: center;">
      <el-button type="primary" @click="showCreateDialog">添加知识库</el-button>
      <el-button @click="resetPagination">查询所有知识库</el-button>
      <el-input
          v-model="searchKeyword"
          placeholder="按问题关键词搜索"
          style="width: 200px; margin-left: 10px"
          @keyup.enter="fetchKnowledgeBasesByKeyword"
      />
      <el-select
          v-model="searchCategory"
          placeholder="按分类筛选"
          style="width: 150px; margin-left: 10px"
          clearable
      >
        <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>

    <!-- 分页组件 -->
    <el-pagination
        v-if="totalRecords > 0"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecords"
    />

    <!-- 新增知识库表单对话框 -->
    <el-dialog title="添加知识库" v-model="dialogVisible" width="50%">
      <el-form :model="knowledgeBaseForm" :rules="rules" ref="formRef">
        <el-form-item label="问题" prop="question">
          <el-input v-model="knowledgeBaseForm.question" placeholder="请输入问题" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="knowledgeBaseForm.answer" placeholder="请输入答案" type="textarea" :rows="10" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="knowledgeBaseForm.category" placeholder="请选择分类">
            <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑知识库表单对话框 -->
    <el-dialog title="编辑知识库" v-model="editDialogVisible" width="50%">
      <el-form :model="editKnowledgeBaseForm" :rules="rules" ref="editFormRef">
        <el-form-item label="问题" prop="question">
          <el-input v-model="editKnowledgeBaseForm.question" placeholder="请输入问题" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="editKnowledgeBaseForm.answer" placeholder="请输入答案" type="textarea" :rows="10" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="editKnowledgeBaseForm.category" placeholder="请选择分类">
            <el-option v-for="item in categories" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateKnowledgeBase">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";
import dayjs from "dayjs";

// 从本地存储获取token
const getToken = () => localStorage.getItem('token') || '';

// 数据状态
const knowledgeBases = ref([]);
const loading = ref(false);
const searchKeyword = ref('');
const searchCategory = ref('');
const formRef = ref(null);
const editFormRef = ref(null);

// 分页状态
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

// 对话框状态
const dialogVisible = ref(false);
const editDialogVisible = ref(false);
const isEdit = ref(false);

// 分类选项
const categories = ref([
  { label: '账号问题', value: 'account' },
  { label: '充值问题', value: 'payment' },
  { label: '游戏玩法', value: 'gameplay' },
  { label: 'BUG反馈', value: 'bug' },
  { label: '其他', value: 'other' }
]);

// 表单数据
const knowledgeBaseForm = reactive({
  id: null,
  question: '',
  answer: '',
  category: 'other'
});

const editKnowledgeBaseForm = reactive({
  id: null,
  question: '',
  answer: '',
  category: 'other'
});

// 表单验证规则
const rules = {
  question: [{ required: true, message: '请输入问题', trigger: 'blur' }],
  answer: [{ required: true, message: '请输入答案', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }]
};

// 格式化文本（超出显示省略号）
const formatText = (text, length = 50) => {
  if (!text) return '无内容';
  return text.length > length ? text.substring(0, length) + '...' : text;
};

// 获取所有知识库（带分页）
const fetchAllKnowledgeBases = async (page = currentPage.value, size = pageSize.value) => {
  try {
    loading.value = true;
    const params = {
      page,
      pageSize: size,
      sort: 'id',
      order: 'desc'
    };

    // 添加搜索条件
    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }
    if (searchCategory.value) {
      params.category = searchCategory.value;
    }

    const response = await request.get('customer-service/knowledge-bases', {
      params,
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200 && response.data && response.data.records) {
      knowledgeBases.value = response.data.records;
      totalRecords.value = response.data.total;

      if (knowledgeBases.value.length === 0 && page > 1) {
        ElMessage.warning('当前页没有数据');
        currentPage.value = Math.max(1, page - 1);
        return fetchAllKnowledgeBases(currentPage.value, pageSize.value);
      } else if (knowledgeBases.value.length === 0) {
        ElMessage.info('暂无知识库条目');
      } else {
        ElMessage.success('获取知识库成功');
      }
    } else {
      knowledgeBases.value = [];
      totalRecords.value = 0;
      ElMessage.warning('获取知识库失败');
    }
  } catch (error) {
    console.error('获取知识库失败:', error);
    handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 按关键词搜索知识库（带分页）
const fetchKnowledgeBasesByKeyword = async () => {
  const keyword = searchKeyword.value.trim();
  if (!keyword) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }

  // 重置分页到第一页
  currentPage.value = 1;

  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      sort: 'id',
      order: 'desc',
      keyword: keyword
    };

    if (searchCategory.value) {
      params.category = searchCategory.value;
    }

    const response = await request.get('customer-service/knowledge-bases', {
      params,
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200 && response.data && response.data.records) {
      knowledgeBases.value = response.data.records;
      totalRecords.value = response.data.total;

      if (knowledgeBases.value.length === 0) {
        ElMessage.info(`未找到包含"${keyword}"的知识库条目`);
      } else {
        ElMessage.success(`搜索"${keyword}"成功，共${totalRecords.value}条记录`);
      }
    } else {
      knowledgeBases.value = [];
      totalRecords.value = 0;
      ElMessage.warning(`未找到包含"${keyword}"的知识库条目`);
    }
  } catch (error) {
    console.error('搜索知识库失败:', error);
    handleApiError(error);
  } finally {
    loading.value = false;
  }
};

// 显示创建对话框
const showCreateDialog = () => {
  dialogVisible.value = true;
  isEdit.value = false;
  resetForm(knowledgeBaseForm);

  nextTick(() => {
    const questionInput = document.querySelector('.knowledge-base-manage textarea[placeholder="请输入问题"]');
    if (questionInput) questionInput.focus();
  });
};

// 显示编辑对话框
const showEditDialog = (knowledgeBase) => {
  editDialogVisible.value = true;
  isEdit.value = true;

  editKnowledgeBaseForm.id = knowledgeBase.id;
  editKnowledgeBaseForm.question = knowledgeBase.question;
  editKnowledgeBaseForm.answer = knowledgeBase.answer;
  editKnowledgeBaseForm.category = knowledgeBase.category;
};

// 重置表单数据
const resetForm = (form) => {
  form.id = null;
  form.question = '';
  form.answer = '';
  form.category = 'other';
};

// 统一处理API错误
const handleApiError = (error) => {
  if (error.response) {
    const { status, data } = error.response;
    if (status === 401) {
      ElMessage.error('未授权，请重新登录');
      setTimeout(() => {
        window.location.href = '/login';
      }, 2000);
    } else if (data && data.message) {
      ElMessage.error(data.message);
    } else {
      ElMessage.error(`请求失败: ${status} ${error.message}`);
    }
  } else {
    ElMessage.error('网络连接失败，请检查网络设置');
  }
};

// 提交添加知识库表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    const response = await request.post('customer-service/knowledge-base', {
      ...knowledgeBaseForm
    }, {
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200) {
      ElMessage.success('添加知识库成功');
      dialogVisible.value = false;
      await fetchAllKnowledgeBases(currentPage.value, pageSize.value);
    } else {
      ElMessage.error(response.message || '添加知识库失败');
    }
  } catch (error) {
    console.error('添加知识库出错:', error);
    handleApiError(error);
  }
};

// 提交编辑知识库表单
const updateKnowledgeBase = async () => {
  try {
    await editFormRef.value.validate();
    const response = await request.put('customer-service/knowledge-base', {
      ...editKnowledgeBaseForm
    }, {
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200) {
      ElMessage.success('更新知识库成功');
      editDialogVisible.value = false;
      await fetchAllKnowledgeBases(currentPage.value, pageSize.value);
    } else {
      ElMessage.error(response.message || '更新知识库失败');
    }
  } catch (error) {
    console.error('更新知识库出错:', error);
    handleApiError(error);
  }
};

// 删除知识库
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该知识库条目吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const response = await request.delete(`customer-service/knowledge-base/${id}`, {
      headers: { 'Authorization': getToken() }
    });

    if (response.code === 200) {
      ElMessage.success('删除知识库成功');
      await fetchAllKnowledgeBases(currentPage.value, pageSize.value);
    } else {
      ElMessage.error(response.message || '删除知识库失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除知识库出错:', error);
      handleApiError(error);
    }
  }
};

// 重置分页到第一页
const resetPagination = () => {
  currentPage.value = 1;
  fetchAllKnowledgeBases();
};

// 每页数量改变时的处理
const handlePageSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  fetchAllKnowledgeBases(currentPage.value, pageSize.value);
};

// 当前页码改变时的处理
const handleCurrentPageChange = (newPage) => {
  currentPage.value = newPage;
  fetchAllKnowledgeBases(currentPage.value, pageSize.value);
};

onMounted(() => {
  // 检查登录状态
  if (!getToken()) {
    ElMessage.warning('请先登录');
    setTimeout(() => {
      window.location.href = '/login';
    }, 2000);
    return;
  }

  fetchAllKnowledgeBases();
});
</script>

<style scoped>
.knowledge-base-manage {
  padding: 20px;
}

.empty-state {
  margin-top: 20px;
  text-align: center;
}

.text-ellipsis {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}
</style>